import promise from 'es6-promise'
import fetch from 'isomorphic-fetch';


promise.polyfill();

export const fetchJson = (options) => {

  options.url = "/papers"+options.url;
  let { url, type, data, ...others } = options;
  Loading(true);
  let opts = {
    ...others,
    method: type || 'get',
    _url:url,
    credentials: 'include',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }
  }
  if (['POST', 'PUT'].indexOf(opts.method.toUpperCase()) >= 0) {
    opts.body = JSON.stringify(data);
  };

  fetch(url, opts)
    .then(resData => toJson(resData, opts))
    .then(resData => resHandler(resData, opts))
    .catch(error => errorHandler(error, opts))
}

function toJson(resp, options) {

  if (resp.status >= 400) {
    return errorHandler(null, options, resp.status)
  }
  return resp.json()
}

// 请求成功处理
function resHandler(resData, options) { 
  Loading(false);
  if (resData.status && resData.status != 200) {
    return errorHandler(resData.error, options, resData.status);
  }
  if (!resData || resData.code > 20000) {
    options.error && options.error(resData);
    console.log(resData.message);
  } else {
    options.success && options.success(resData);
  };
}

// 异常处理
function errorHandler(error, options, status) {
  Loading(false);
  options.error && options.error(error);
  console.log(`网络异常，请稍后重试(${status})`);
}


function Loading(IsShow){

    var loading = document.querySelector('#loadTips');
    if(!loading&&!IsShow){
      return ;
    };
    if(loading){
        loading.className=!IsShow?"wb-fix hide":"wb-fix";
    }else{
        var str = '<div class="ui-loading ui-loading-open" ><div class="ui-loading-container"><div class="ui-loading-items" ><div class="ui-loading-item" ></div><div class="ui-loading-item" ></div><div class="ui-loading-item" ></div><div class="ui-loading-item" ></div><div class="ui-loading-item" ></div><div class="ui-loading-item" ></div><div class="ui-loading-item" ></div><div class="ui-loading-item" ></div><div class="ui-loading-item" ></div><div class="ui-loading-item" ></div><div class="ui-loading-item"></div><div class="ui-loading-item"></div></div></div><div class="ui-mask transparent"></div></div>';
        var CreateLoad = document.createElement("div");
        CreateLoad.id="loadTips";
        CreateLoad.className=!IsShow?"wb-fix hide":"wb-fix";
        CreateLoad.innerHTML=(str);
        document.body.appendChild(CreateLoad);
    };
};